package com.tinem.platform.service.robot.im.adaptation.hjxc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tinem.platform.service.robot.im.core.ReplyMessage;
import jakarta.annotation.Resource;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class HjxcRobotAdaptation implements ApplicationRunner, ApplicationListener<ReplyMessage> {

    @Resource
    Api api;

    @Resource
    OnMessage onMessage;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(api);
        String res = api.token();
        JSONObject o = JSON.parseObject(res);
        api.access_token = o.getString("access_token");
        api.access_token = api.login().getString("accessToken");
        JSONObject userInfo = api.userInfo();
        api.access_token = userInfo.getString("accessToken");
        api.userInfo = userInfo;
        onMessage.onMessage();
    }

    @Scheduled(cron = "0 0 3 * * ?")
    public void refresh(){
        api.access_token = api.userInfo().getString("accessToken");
    }

    @Override
    public void onApplicationEvent(ReplyMessage event) {
        if(!event.getMessage().getClientId().equals(api.hjxcAutoProperties.clientId())){
            return;
        }
        api.sendMessage(event.getMessage().getFromUser().getClientUserId(),"",event.getContent());
    }
}
